<?php

namespace App\Providers;

use Exception;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        //慢sql日志
        DB::listen(
            function ($query) {
                $tmp = str_replace('?', '"' . '%s' . '"', $query->sql);
                $qBindings = [];
                foreach ($query->bindings as $key => $value) {
                    if (is_numeric($key)) {
                        $qBindings[] = $value;
                    } else {
                        $tmp = str_replace(':' . $key, '"' . $value . '"', $tmp);
                    }
                }

                try {
                    if ($query->time > 500) {
                        if (!empty($qBindings) && !empty($tmp)) {
                            $tmp = vsprintf($tmp, $qBindings);
                            $tmp = str_replace("\\", "", $tmp);
                        }

                        $func = "debug";
                        if ($query->time > 1000) {
                            $func = 'error';
                        }

                        Log::channel("log")->$func('sql : ' . $query->time . 'ms; ' . $tmp . "\n\t");
                    }
                } catch (Exception $e) {
                    Log::channel("log")->error('exception : ' . $e->getMessage());
                }
            }
        );

    }
}
